<?php

namespace app\admin\queue;

use think\queue\Job;

class Template
{
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        $isDone = $this->doJob($data);
        if ($isDone) {
            // 删除任务
            $job->delete();
        } else {
            if ($job->attempts() > 3) {
                // 重新发布任务，延迟1秒
                $job->release(1);
            }
        }
    }

    /* 业务逻辑 */
    private function doJob($data)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $data['token'];
        $template_id = 'YOTx9otzTv2v6j4gPT0gyYf45kx9LJcNSQEx3Pv3NSU';
        if ($data['url'] != '') {
            $param = [
                'touser' => $data['openid'],
                'template_id' => $template_id,
                'url' => $data['url'],
                'data' => [
                    'first' => [
                        'value' => $data['first'],
                        'color' => '#575757',
                    ],
                    'keyword1' => [
                        'value' => $data['keyword1'],
                        'color' => '#575757',
                    ],
                    'keyword2' => [
                        'value' => $data['keyword2'],
                        'color' => '#FF0000',
                    ],
                    'remark' => [
                        'value' => $data['remark'],
                        'color' => '#575757',
                    ],
                ],
            ];
        } else {
            $param = [
                'touser' => $data['openid'],
                'template_id' => $template_id,
                'data' => [
                    'first' => [
                        'value' => $data['first'],
                        'color' => '#575757',
                    ],
                    'keyword1' => [
                        'value' => $data['keyword1'],
                        'color' => '#575757',
                    ],
                    'keyword2' => [
                        'value' => $data['keyword2'],
                        'color' => '#FF0000',
                    ],
                    'remark' => [
                        'value' => $data['remark'],
                        'color' => '#575757',
                    ],
                ],
            ];
        }

        $errcode = curl($url, $param);
        return ($errcode['errcode'] == 0) ? true : false;
    }
}
